<?php
/**
 * Descript:
 * User: lufeng501206@gmail.com
 * Date: 2017/3/17 23:03
 */

namespace App\Repositories;


use App\Models\Admin\Tasks;
use App\Models\ExtractCash;
use App\Models\Home\Orders;
use App\Models\Home\User;
use Carbon\Carbon;

class TasksRepos
{
    /**
     * 获取任务列表
     * @param array $conditions
     * @return mixed
     */
    public function getTasksLists($conditions = array(), $returnLists = true)
    {
        $taskModel = Tasks::select('*', 'tasks.id as id', 'admin_users.id as userid', 'tasks.created_at as created_at')
            ->leftJoin('admin_users', 'admin_users.id', '=', 'tasks.release_userid')
            ->where('tasks.id', '>', 0);

        // 发布者
        if (!empty($conditions['release_userid'])) {
            $taskModel = $taskModel->where('release_userid', $conditions['release_userid']);
        }

        // 单个标签
        if (!empty($conditions['label'])) {
            $taskModel = $taskModel->where('label', $conditions['label']);
        }

        // 开始时间
        if (!empty($conditions['begin_time'])) {
            $taskModel = $taskModel->where('release_time', '<=', $conditions['begin_time']);
        }

        //根据标签查询
        if (!empty($conditions['lables']) && !strpos($conditions['lables'], '"0"')) {
            $lables = json_decode($conditions['lables'], true);
            $taskModel = $taskModel->where(function ($query) use ($lables) {
                foreach ($lables as $k => $v) {
                    $query = $query->orWhere('label', $v);
                }
            });
        }
        //排序
        if (!empty($conditions['orderType'])) {
            $orderType = $conditions['orderType'];
            if ($orderType == 1) { //综合排序
                //...
            } elseif ($orderType == 2) { //最新发布时间
                $taskModel = $taskModel->orderBy('tasks.created_at', 'desc');
            } elseif ($orderType == 3) { //佣金
                $taskModel = $taskModel->orderBy('money', 'desc');
            }
        }
        if (!empty($conditions['title'])) {
            $title = $conditions['title'];
            $taskModel = $taskModel->where('title', 'like', '%' . $title . '%');
        }
        if (!empty($conditions['state'])) {
            $taskModel = $taskModel->where('state', '=', $conditions['state']);
        }
        if (!empty($conditions['state_arr'])) {
            $taskModel = $taskModel->whereIn('state', $conditions['state_arr']);
        }
        //统计总数
        if (!$returnLists) {
            $total = $taskModel->count();
        }
        if (!empty($conditions['start'])) {
            $taskModel = $taskModel->offset($conditions['start']);
        }

        if (!empty($conditions['limit'])) {
            $taskModel = $taskModel->limit($conditions['limit']);
        }

        if (!empty($conditions['id'])) {
            $id = $conditions['id'];
            $taskModel = $taskModel->where('tasks.id', $id);
            $lists = $taskModel->take(1)->get()->toArray();
        } else {
            $lists = $taskModel->orderBy('tasks.id', 'desc')->get()->toArray();
        }

        if (!empty($lists)) {
            foreach ($lists as $key => &$value) {
                unset($value['password']);
                $value['images_arr'] = !empty($value['images']) ? json_decode($value['images'], true) : [];
                $value['hours'] = $value['audit_time'] / 3600;
                $taskDetailModel = Tasks::find($value['id']);
                if (!empty($taskDetailModel)) {
                    $value['used_nums'] = $taskDetailModel->orders->count();
                } else {
                    $value['used_nums'] = 0;
                }
            }
        }
        if ($returnLists) {
            return $lists;
        } else {
            $data['total'] = $total;
            $data['lists'] = $lists;
            return $data;
        }
    }

    /**
     * 获取用户任务列表
     * @param $id
     * @return mixed
     */
    public function getTasksListsByUserId($id, $conditions = [])
    {
        $orderModel = Orders::select("*", "tasks.id as task_id", "orders.id as id", "orders.state as state","orders.updated_at as updated_at");
        $orderModel = $orderModel->leftJoin('tasks', 'tasks.id', '=', 'orders.task_id');
        $orderModel = $orderModel->leftJoin('home_users', 'home_users.id', '=', 'orders.user_id');
        if (!empty($conditions['state'])) {
            if ($conditions['state'] == 3) {
                $orderModel = $orderModel->whereIn('orders.state', [3, 4]);
            } else {
                $orderModel = $orderModel->where('orders.state', $conditions['state']);
            }
        }
        if (!empty($conditions['month'])) {
            $startTime = Carbon::createFromTimestamp(strtotime($conditions['month']))->firstOfMonth()->toDateString();
            $endTime = Carbon::createFromTimestamp(strtotime($conditions['month']))->endOfMonth()->toDateString();
            $orderModel = $orderModel->whereBetween('orders.updated_at', [$startTime, $endTime]);
        }
        $orderModel = $orderModel->where('user_id', $id);
        $lists = $orderModel->get()->toArray();
        if (!empty($lists)) {
            foreach ($lists as $key => &$value) {
                $taskDetailModel = Tasks::find($value['task_id']);
                if (!empty($taskDetailModel)) {
                    $value['used_nums'] = $taskDetailModel->orders->count();
                } else {
                    $value['used_nums'] = 0;
                }
            }
        }
        return $lists;
    }

    /**
     * 获取任务详情
     * @param $id
     * @return mixed
     */
    public function getTaskInfo($id)
    {
        $info = Tasks::findOrFail($id)->toArray();
        return $info;
    }

    /**
     * 获取用户的任务状态
     * @param $taskId
     * @param $userId
     * @return int
     */
    public function getUserTaskDetail($taskId, $userId)
    {
        $res = Orders::where('user_id', $userId)->where('task_id', $taskId)->first();
        if (!empty($res)) {
            return $res->state;
        } else {
            return 0;
        }
    }

    /**
     * 获取订单信息列表
     * @param $taskId
     * @return mixed
     */
    public function getOrderLists($taskId, $conditions = [], $returnLists = false)
    {
        $orderModel = Orders::select('*', 'orders.id as id', 'orders.state as state', 'orders.mobile as order_mobile', 'orders.created_at as created_at')
            ->where('task_id', $taskId)
            ->leftJoin('home_users', 'home_users.id', '=', 'orders.user_id');

        if (!empty($conditions['order_lists'])) {
            $orderModel = $orderModel->whereIn('orders.id', $conditions['order_lists']);
        }

        if (!empty($conditions['state'])) {
            $orderModel = $orderModel->where('orders.state', $conditions['state']);
        }

        if (!empty($conditions['state_arr'])) {
            $orderModel = $orderModel->whereIn('orders.state', $conditions['state_arr']);
        }

        if (!empty($conditions['user_id'])) {
            $orderModel = $orderModel->where('orders.id', $conditions['user_id']);
        }

        if (!empty($conditions['name'])) {
            $orderModel = $orderModel->where('home_users.name', 'like', '%' . $conditions['name'] . '%');
        }

        if (!$returnLists) {
            $total = $orderModel->count();
        }

        if (!empty($conditions['start'])) {
            $orderModel = $orderModel->offset($conditions['start']);
        }

        if (!empty($conditions['limit'])) {
            $orderModel = $orderModel->limit($conditions['limit']);
        }

        $lists = $orderModel->get()->toArray();

        if (!empty($lists) && is_array($lists)) {
            foreach ($lists as $k => &$value) {
                unset($value['password']);
                $value['images'] = !empty($value['images']) ? json_decode($value['images'], true) : [];
            }
        }

        if ($returnLists) {
            return $lists;
        } else {
            $data['total'] = $total;
            $data['lists'] = $lists;
            return $data;
        }
    }

    /**
     * 获取已经完成任务列表
     * @param $taskId
     * @return array
     */
    public function getFinishOrder($taskId)
    {
        $orderModel = Orders::select('home_users.name', 'tasks.money', 'tasks.title');
        $orderModel = $orderModel->leftJoin('tasks', 'tasks.id', '=', 'orders.task_id');
        $orderModel = $orderModel->leftJoin('home_users', 'home_users.id', '=', 'orders.user_id');
        $orderModel = $orderModel->where('orders.task_id', $taskId)->where('orders.state', 4);
        $lists = $orderModel->get()->toArray();
        return $lists;
    }

    /**
     * 获取任务订单用户提交数据
     * @param $taskId
     * @param $userId
     * @return mixed
     */
    public function getUserFinishData($taskId, $userId)
    {
        $orderModel = Orders::select("state", "images", "mobile");
        $data = $orderModel->where('task_id', $taskId)->where('user_id', $userId)->first();
        if (!empty($data)) {
            $data = $data->toArray();
            $images = json_decode($data['images'], true);
            if (!empty($images) && is_array($images)) {
                foreach ($images as &$image) {
                    $image = env('STATIC_URL') . $image;
                }
            }
            $data['images'] = $images;
        }
        return $data;
    }

    public function getCashLists($conditions = array())
    {
        $cashModel = ExtractCash::select('*', 'extract_cash.id as id', 'extract_cash.balance as extract_balance', 'extract_cash.created_at as created_at');
        $cashModel = $cashModel->leftJoin('home_users', 'home_users.id', '=', 'extract_cash.user_id');
        if (!empty($conditions['state'])) {
            $cashModel = $cashModel->whereIn('extract_state', $conditions['state']);
        }
        if (!empty($conditions['user_id'])) {
            $cashModel = $cashModel->where('user_id', $conditions['user_id']);
        }
        if (!empty($conditions['id'])) {
            $cashModel = $cashModel->where('extract_cash.id', $conditions['id'])->limit(1);
        }
        $lists = $cashModel->get()->toArray();
        if (!empty($lists)) {
            foreach ($lists as $key => &$value) {
                $value['transform_balance'] = $this->getUserMoney($value['user_id'], 1);
                $value['transform_cash'] = $this->getUserMoney($value['user_id'], 2);
            }
        }
        return $lists;
    }

    /**
     * 获取用户的结算和已到账的金额
     * @param $userId
     * @param $type
     * @return int
     */
    public function getUserMoney($userId, $type)
    {
        $money = 0;
        if ($type == 1) {
            $money = ExtractCash::select('*')->where('user_id', $userId)->whereIn('extract_state', [1, 2])->sum('cash_money');
        }
        if ($type == 2) {
            $money = ExtractCash::select('*')->where('user_id', $userId)->whereIn('extract_state', [2])->sum('cash_money');
        }
        return $money;
    }

    /**
     * 终止所有订单
     *
     * @param $taskId
     */
    public function killAllOrders($taskId)
    {
        $orderLists = Orders::where('task_id',$taskId)->get();
        if (!empty($orderLists)) {
            $orderLists = $orderLists->toArray();
            if (is_array($orderLists)) {
                foreach ($orderLists as $key => $value) {
                    $orderModel = Orders::find($value['id']);
                    if ($orderModel->state != 4) {
                        $orderModel->state = 3; //全部驳回终止
                        $orderModel->save();
                    }
                }
            }
        }
    }
}